(function () {
    var init, isLoginForm, prepareForm, getInput;

    init = function () {
        var forms, i;
        forms = this.document.getElementsByTagName('form');
        for (i = forms.length - 1; i >= 0; i-= 1) {
            if (isLoginForm(forms[i])) {
                prepareForm(forms[i]);
            }
        }
    };

    getInput = function (form, name) {
        var inputs, i;
        inputs = form.getElementsByTagName('input');
        for (i = inputs.length - 1; i >= 0; i -= 1) {
            if (inputs[i].name === name) {
                return inputs[i];
            }
        }
        return null;
    };

    prepareForm = function (form) {
        var input, SHA1;
        input = this.document.createElement('input');
        input.type = 'hidden';
        input.name = 'sendTimestamp';
        input.value = parseInt((new Date()).getTime() / 1000, 10);
        form.appendChild(input);
        SHA1 = this.SHA1;
        form.onsubmit = function () {
            var timestamp, password, sendTimestamp;
            timestamp = getInput(form, 'timestamp');
            if (timestamp == null) {
                return true;
            }
            sendTimestamp = getInput(form, 'sendTimestamp');
            sendTimestamp.value = parseInt((new Date()).getTime() / 1000) -
                    parseInt(sendTimestamp.value, 10) +
                    parseInt(timestamp.value, 10);
            password = getInput(form, 'password');
            password.value = SHA1(sendTimestamp.value.toString() +
                    SHA1(password.value.toString()));
            return true;
        };
    };

    isLoginForm = function (form) {
        var inputs, i;
        inputs = form.getElementsByTagName('input');
        for (i = inputs.length - 1; i >= 0; i -= 1) {
            if ((inputs[i].type.toLowerCase() === 'hidden') &&
                    (inputs[i].name === 'event') &&
                    (inputs[i].value === 'login')) {
                return true;
            }
        }
        return false;
    };

    if (this.addEventListener instanceof Function) {
        this.addEventListener('load', init, false);
    } else {
        this.attachEvent('onload', init);
    }
}());